package com.dinstar.dinlink.ui.home;


import static androidx.core.content.ContextCompat.startForegroundService;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.dinstar.dinlink.R;
import com.dinstar.dinlink.activity.MainActivity;
import com.dinstar.dinlink.databinding.FragmentHomeBinding;
import com.dinstar.dinlink.server.MyForegroundService;
import com.dinstar.dinlink.server.MyService;
import com.dinstar.dinlink.ui.LinphoneMainActivity;
import com.dinstar.dinlink.utils.PermissionsUtils;
import com.dinstar.dinlink.utils.ServiceUtils;
import com.dinstar.dinlink.weiget.floatingwindow.VoiceActivity;
import com.mixpush.core.GetRegisterIdCallback;
import com.mixpush.core.MixPushClient;
import com.mixpush.core.MixPushPlatform;

import core.library.com.widget.toupload.constant.UiType;
import core.library.com.widget.toupload.model.UiConfig;
import core.library.com.widget.toupload.model.UpdateConfig;
import core.library.com.widget.toupload.update.UpdateAppUtils;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class HomeFragment extends Fragment {
    private static String TAG  = HomeFragment.class.getName();
    private FragmentHomeBinding binding;

    private String[] premissions = new String[]{
            Manifest.permission.CAMERA,
    };


    private String[] getStorageCompatPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return new String[]{
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_AUDIO,};
        } else {
            return new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,};
        }
    }




    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        init();
        initLister();

//        mLifecycleRegistry = new LifecycleRegistry(this);
//        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
//        myLifecycleObserver = new MyLifecycleObserver();
//        mLifecycleRegistry.addObserver(myLifecycleObserver);
        return root;
    }

    /**
     * 开启相互守护的两个服务
     */
    private void startDoubleRemoteService(){
        ServiceUtils.startNormalRemoteService(requireActivity());
        ServiceUtils.startGuardRemoteService(requireActivity());
    };

    private void initLister() {


        binding.btnDoubleServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startDoubleRemoteService();
            }
        });

        binding.btnNotifcation.setOnClickListener(new View.OnClickListener() {  // 厂商推送注册
            @Override
            public void onClick(View v) {
                if (notificationMixPushPlatform != null) {
                    Toast.makeText(requireActivity(),"注册成功"+notificationMixPushPlatform.getRegId(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(requireActivity(),"注册失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
        binding.btnLockScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(requireActivity(), MyService.class);
                requireActivity().startService(intent); //启动后台服务
            }
        });

        binding.btnLinPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext(), LinphoneMainActivity.class);
                i.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                startActivity(i);
            }
        });

        binding.textHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent i = new Intent(getContext(), FloatingWindowService.class);
//                i.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//                startActivity(i);
                // 启动前台服务
                Intent serviceIntent = new Intent(requireActivity(), MyForegroundService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    requireActivity(). startForegroundService(serviceIntent); // Android 8.0及以上使用startForegroundService
                } else {
                    requireActivity(). startService(serviceIntent); // Android 8.0以下使用startService
                }

            }
        });


        binding.btnShowFloat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(requireActivity(), VoiceActivity.class);
                startActivity(intent);
            }
        });

        binding.btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(binding.downLoadEdt.getText().toString())){
                    Toast.makeText(requireActivity(),"地址不能为空",Toast.LENGTH_LONG).show();
                    return;
                }

                if (!binding.downLoadEdt.getText().toString().startsWith("http")){
                    Toast.makeText(requireActivity(),"地址格式不规范",Toast.LENGTH_LONG).show();
                    return;
                }


                // 定义描述和标题
                String desc = "我们需要存储来对应用进行更新";
                String title = "权限请求";

                var uiconfig = new UiConfig();
                uiconfig.setUiType(UiType.PLENTIFUL);

                UpdateConfig updateConfig = new UpdateConfig();
                updateConfig.setForce(true);
                updateConfig.setCheckWifi(true);
                updateConfig.setNeedCheckMd5(false);
                updateConfig.setShowNotification(true);
                updateConfig.setNotifyImgRes(R.mipmap.ic_launcher);

                // 定义回调函数
                Function0<Unit> onGranted = new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        Toast.makeText(requireActivity(),"所有权限已授予",Toast.LENGTH_LONG).show();
                        UpdateAppUtils
                                .getInstance()
                                .apkUrl(binding.downLoadEdt.getText().toString())
                                .updateConfig(updateConfig)
                                .uiConfig(uiconfig)
                                .updateTitle("版本更新提示")
                                .updateContent("版本更新的内容")
                                .update();
                        return Unit.INSTANCE;
                    }
                };

                Function0<Unit> onDenied = new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        Toast.makeText(requireActivity(),"权限被拒绝",Toast.LENGTH_LONG).show();
                        return Unit.INSTANCE;
                    }
                };

                Function0<Unit> onDeniedWithoutRequest = new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        System.out.println("用户拒绝了权限请求");
                        Toast.makeText(requireActivity(),"用户拒绝了权限请求",Toast.LENGTH_LONG).show();
                        return Unit.INSTANCE;
                    }
                };
                PermissionsUtils.INSTANCE.handleRequestPermissions(requireActivity(),getStorageCompatPermission() , desc, title, onGranted, onDenied, onDeniedWithoutRequest);
            }
        });

    }



     private MixPushPlatform notificationMixPushPlatform;
    private void  init(){
        MixPushClient.getInstance().getRegisterId(requireActivity(),new GetRegisterIdCallback(){
            @Override
            public void callback(@Nullable MixPushPlatform platform) {
                notificationMixPushPlatform = platform;
            }
        });

//        MixPushClient.getInstance().getRegisterId(this, object : GetRegisterIdCallback() {
//            override fun callback(platformMix: MixPushPlatform?) {
//                notificationMixPushPlatform = platformMix
//                updateRegId()
//            }
//        })


        binding. requsePermsin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
/**
 *kotlin  使用方法
 */
//                handleRequestPermissions(
//                        Manifest.permission.CAMERA, desc = "扫描车架号需要相机权限", onGranted = {
//
//                        }, onDenied = {
//                                ToastUtils.showShort(this, "无相机权限，扫描失败")
//                        }, onDeniedWithoutRequest = {
//                                ToastUtils.showShort(this, "未获取到相机权限，扫描失败")
//                        })

/**
* java 使用方法
*/
                // 定义权限数组
                String[] permissions = {"android.permission.CAMERA"};
                // 定义描述和标题
                String desc = "我们需要这些权限来正常使用应用";
                String title = "权限请求";
                // 定义回调函数
                Function0<Unit> onGranted = new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        System.out.println("所有权限已授予");
                        Toast.makeText(requireActivity(),"所有权限已授予",Toast.LENGTH_LONG).show();
                        return Unit.INSTANCE;
                    }
                };

                Function0<Unit> onDenied = new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        Toast.makeText(requireActivity(),"权限被拒绝",Toast.LENGTH_LONG).show();
                        return Unit.INSTANCE;
                    }
                };

                Function0<Unit> onDeniedWithoutRequest = new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        System.out.println("用户拒绝了权限请求");
                        Toast.makeText(requireActivity(),"用户拒绝了权限请求",Toast.LENGTH_LONG).show();
                        return Unit.INSTANCE;
                    }
                };
                // 调用Kotlin方法
                PermissionsUtils.INSTANCE.handleRequestPermissions(requireActivity(),permissions, desc, title, onGranted, onDenied, onDeniedWithoutRequest);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent serviceIntent = new Intent(requireActivity(), MyForegroundService.class);
        requireActivity().stopService(serviceIntent);
    }


}